﻿using Maxi.Areas.Sistema.Models;
using Maxi.Controllers;
using Maxi.Models;
using Maxi.Models.Banco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Maxi.Areas.Sistema.Controllers
{
    public class ResponsavelController : BaseController
    {
        // GET: Sistema/Responsavel

        private Conexao con = new Conexao();
        public ActionResult Index()
        {
            List<string> breadcrumbs = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>();

            dic.Add("@Url.Content('~/Alunos')", "Alunos");

            breadcrumbs.Add("Home");
            breadcrumbs.Add("Alunos");

            ViewBag.Breadcrumbs = breadcrumbs;
            return View();
        }
        public ActionResult Novo()
        {
            var model = new ResponsavelModel();
            ViewBag.Grupos = con.Tb_Grupo.ToList();
            return View("NovoEditar", model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Salvar(ResponsavelModel model)
        {
            Tb_Responsavel responsavel = null;

            if (con.Tb_Aluno.Any(x => x.UsuarioId == (model.codigo + Extensions.SuResponsavel)))
            {
                responsavel = con.Tb_Responsavel.Where(x => x.IdUsuario == (model.codigo + Extensions.SuResponsavel)).SingleOrDefault();
                con.Entry(responsavel).State = System.Data.Entity.EntityState.Modified;
            }
            else
            {
                responsavel = new Tb_Responsavel();
                string codigo = model.codigo + Extensions.SuResponsavel;
                responsavel.Tb_Usuario = new Tb_Usuario() { Id = codigo };
                responsavel.IdUsuario = codigo;
                con.Tb_Responsavel.Add(responsavel);
            }

            responsavel.Cpf = model.cpf;
            responsavel.Tb_Usuario.Nome = model.nome;
            responsavel.Tb_Usuario.Endereco = model.endereco;
            responsavel.Tb_Usuario.Bairro = model.bairro;
            responsavel.Tb_Usuario.Cidade = model.cidade;
            responsavel.Tb_Usuario.Uf = model.uf;
            responsavel.Tb_Usuario.TipoUsuario = "A";
            responsavel.Tb_Usuario.IdGrupo = 2;
            responsavel.Tb_Usuario.PrimeiroLogin = null;
            responsavel.Tb_Usuario.Cep = model.cep;
            responsavel.Tb_Usuario.DddFixo = model.ddd;
            responsavel.Tb_Usuario.FoneFixo = model.telefone;
            responsavel.Tb_Usuario.Email = model.email;
            con.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult Editar(string id)
        {
            Tb_Responsavel responsavel = con.Tb_Responsavel.Where(x => x.IdUsuario  == id).FirstOrDefault();
            ResponsavelModel model = new ResponsavelModel();
            model.bairro = responsavel.Tb_Usuario.Bairro;
            model.cep = responsavel.Tb_Usuario.Cep;
            model.cidade = responsavel.Tb_Usuario.Cidade;
            model.codigo = responsavel.Tb_Usuario.Id;
            model.cpf = responsavel.Cpf;
            model.ddd = responsavel.Tb_Usuario.DddFixo;
            model.email = responsavel.Tb_Usuario.Email;
            model.endereco = responsavel.Tb_Usuario.Endereco;
            model.grupo = responsavel.Tb_Usuario.IdGrupo.ToString();
            model.nome = responsavel.Tb_Usuario.Nome;
            model.telefone = responsavel.Tb_Usuario.FoneFixo;
            model.uf = responsavel.Tb_Usuario.Uf;
            model.usuario = responsavel.Tb_Usuario.Usuario;

            ViewBag.Grupos = con.Tb_Grupo.ToList();
            return View("NovoEditar", model);
        }

        public ActionResult Excluir(string id)
        {
            Tb_Usuario resp = con.Tb_Usuario.Where(x => x.Id == id).FirstOrDefault();
            con.Tb_Usuario.Remove(resp);
            con.SaveChanges();

            return RedirectToAction("Index");
        }


        public JsonResult List(TableRequestModel req)
        {

            IQueryable<Tb_Responsavel> list = con.Tb_Responsavel.OrderBy(x => x.Tb_Usuario.Nome);

            if (String.IsNullOrWhiteSpace(req.sSearch) == false)
            {
                list = list.Where(x =>
                        x.Tb_Usuario.Nome.Contains(req.sSearch)
                    );
            }

            int total = list.Count();

            list = list.Skip(req.iDisplayStart).Take(req.iDisplayLength);

            var model = new TableResponseModel
            {
                sEcho = req.sEcho,
                iTotalRecords = list.Count(),
                iTotalDisplayRecords = total,
                aaData = from r in list.ToList()
                         select new
                         {
                             CodResp = r.IdUsuario.Replace(Extensions.SuResponsavel, string.Empty),
                             Nome = r.Tb_Usuario.Nome,
                             Endereco = r.Tb_Usuario.Endereco,
                             Cidade = r.Tb_Usuario.Cidade,
                             Fone = r.Tb_Usuario.FoneFixo,
                             EditUrl = Url.RouteUrl("sistema.responsavel.edit", new { id = r.IdUsuario }),
                             DeleteUrl = Url.RouteUrl("sistema.responsavel.excluir", new { id = r.IdUsuario })
                         }
            };


            return Json(model, JsonRequestBehavior.AllowGet);

        }
    }
}